package com.ruoyi.common.utils;


import com.alibaba.fastjson2.JSON;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Component
public class QiniuKodoUtil {
    /**
     * 构造一个带指定 Region 对象的配置类，因为我的是华南机房，所以为Region.region2()
     */
//    Configuration cfg = new Configuration(Region.region2());
    @Value("${qiniu.kodo.accessKey}")
    String accessKey;
    @Value("${qiniu.kodo.secretKey}")
    String secretKey;
    @Value("${qiniu.kodo.bucket}")
    String bucket;
    @Value("${qiniu.kodo.domain}")
    String domain;
    @Value("${qiniu.kodo.hosts}")
    String hosts;
    /**
     * 文件名前缀
     */
    String prefix = "";
    /**
     * 每次迭代的长度限制，最大1000，推荐值 1000
     */
    int limit = 1000;
    /**
     * 指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
     */
    String delimiter = "";

    public String uploadStream(InputStream uploadStream, String targetFileName) {

        if (targetFileName.startsWith("/")) {
            targetFileName = targetFileName.replaceFirst("/", "");
        }
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(domain));
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        try {
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(uploadStream, targetFileName, upToken,null,null);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject (response.bodyString(),DefaultPutRet.class);
            return hosts +"/"+  targetFileName;
        } catch (Exception ex) {
            //Log.error("七牛云oss文件上传失败 {}", ex);
            ex.printStackTrace();
        }
        return null;
    }



}
